package com.eduhzy.ttw.teacher.mvp.presenter;

import android.app.Application;
import android.content.Intent;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.LoginData;
import com.eduhzy.ttw.commonsdk.http.CommonApi;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.utils.Utils;
import com.eduhzy.ttw.teacher.mvp.contract.LoginContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.inject.Inject;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View rootView) {
        super(model, rootView);
    }

    private Map<String, Object> map;

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void login(String user, String pwd, String clientType) {
        String deviceId = SPUtils.getInstance().getString(Constants.DEVICEID, "");
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("userName", user);
        params.put("password", pwd);
        params.put("deviceId", deviceId);
        params.put("clientType", clientType);

        mModel.getLoginData(params)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<LoginData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<LoginData> loginData) {
                        if (loginData.isResult() && loginData.getMessageCode() == 0) {
                            loginType = Constants.LOGIN_NORMAL;
                            dealLogin(loginData.getData(), user, pwd);
                        } else {
                            mRootView.showMessage(loginData.getMessage());
                        }
                    }
                });
    }

    private void dealLogin(LoginData loginData, String user, String pwd) {
        SPUtils.getInstance().put(Constants.LOGIN_TYPE, loginType);
        SPUtils.getInstance().put(Constants.TOKEN, loginData.getAuthId(), SPUtils.getInstance().contains(Constants.TOKEN));
        SPUtils.getInstance().put(Constants.USERID, String.valueOf(loginData.getUserId()), SPUtils.getInstance().contains(Constants.USERID));
        SPUtils.getInstance().put(Constants.USERNICKNAME, String.valueOf(loginData.getUserNickName()), SPUtils.getInstance().contains(Constants.USERNICKNAME));
        SPUtils.getInstance().put(Constants.TEMPAVATAR, loginData.getTempAvatar(), SPUtils.getInstance().contains(Constants.TEMPAVATAR));
        if (!StringUtils.isTrimEmpty(user)) {
            SPUtils.getInstance().put(Constants.USERNAME, user, SPUtils.getInstance().contains(Constants.USERNAME));
        }
        if (!StringUtils.isTrimEmpty(pwd)) {
            SPUtils.getInstance().put(Constants.PASSWORD, pwd, SPUtils.getInstance().contains(Constants.PASSWORD));
        }
        Utils.navigationWithTitle(RouterHub.APP_HOMEACTIVITY, loginData.getUserNickName());
//            Message msg = new Message();
//            msg.what = EventBusTags.LOGIN_SUCCESS;
//            EventBus.getDefault().post(msg, EventBusTags.LOGIN);
        mRootView.killMyself();

    }


    public void thirdLogin(String third, int userNameType) {
        map = new LinkedHashMap<>();
        map.put("userNameType", userNameType);
        map.put("deviceId", SPUtils.getInstance().getString(Constants.DEVICEID));
        Platform platform = ShareSDK.getPlatform(third);
        if (!platform.isClientValid()) {
            RxUtil.showTipDialog(mRootView.getActivity(), 3, third.contains("QQ") ? "QQ未安装,请先安装QQ" : "微信未安装，请先安装微信");
            return;
        }
        mRootView.showLoading();
        platform.setPlatformActionListener(mPlatformActionListener);
        platform.showUser(null);
    }

    private int loginType;
    PlatformActionListener mPlatformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            map.put("openid", platform.getDb().getUserId());
            if (platform instanceof QQ) {
                loginType = Constants.LOGIN_THIRD_QQ;
            } else if (platform instanceof Wechat) {
                loginType = Constants.LOGIN_THIRD_WX;
            }
            SPUtils.getInstance().put(Constants.OPENID, platform.getDb().getUserId());
            loginByThird();
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            throwable.printStackTrace();
            mRootView.hideLoading();
        }

        @Override
        public void onCancel(Platform platform, int i) {
            mRootView.hideLoading();
        }
    };

    private void loginByThird() {
        mModel.getThirdLoginData(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
//                .doOnSubscribe(disposable -> )
//                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<LoginData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<LoginData> loginData) {
                        if (!loginData.isResult() && loginData.getMessageCode() == CommonApi.NETWORK_ERROR_NOT_USER) {
                            ARouter.getInstance()
                                    .build(RouterHub.APP_REGISTERACTIVITY)
                                    .withString(Intent.EXTRA_TITLE, "绑定")
                                    .withString(Constants.OPENID, (String) map.get("openid"))
                                    .withInt(Constants.LOGIN_TYPE, Constants.LOGIN_THIRD)
                                    .navigation();

                        } else if (loginData.isResult() && loginData.getMessageCode() == 0) {
                            dealLogin(loginData.getData(), null, null);
                        }
                    }
                });
    }
}
